// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.ListingFather;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.BrandMapper;
import com.fowo.api.mapper.ClassifyMapper;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.mapper.ListingSmallRankMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysRegionMapper;
import com.fowo.api.model.brand.BrandItemVo;
import com.fowo.api.model.brand.BrandSearchParamPo;
import com.fowo.api.model.classify.ClassifyItemVo;
import com.fowo.api.model.classify.ClassifySearchParamPo;
import com.fowo.api.model.listing.father.ListingFatherBatchRelievePairAction;
import com.fowo.api.model.listing.father.ListingFatherExcelPo;
import com.fowo.api.model.listing.father.ListingFatherImportPo;
import com.fowo.api.model.listing.father.ListingFatherItemVo;
import com.fowo.api.model.listing.father.ListingFatherRelievePairAction;
import com.fowo.api.model.listing.father.ListingFatherSearchParamPo;
import com.fowo.api.model.listing.father.ListingFatherSyncAmazonListingAction;
import com.fowo.api.model.listing.father.ListingFatherSyncProductAction;
import com.fowo.api.model.listing.father.ListingFatherVo;
import com.fowo.api.model.listing.small.rank.ListingSmallRankSearchParamPo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.region.SysRegionItemVo;
import com.fowo.api.model.sys.region.SysRegionSearchParamPo;
import com.fowo.api.service.ListingFatherService;
import com.fowo.api.service.ListingSmallRankService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * Listing 服务实现类
 * @author 蜂窝蜜造平台 配置人：陈新新，任凯
 */
@Service
@Slf4j
@DataObjectType(ListingFather.class)
@DS("ds24")
public class ListingFatherServiceImpl
  extends ServiceImpl<ListingFatherMapper, ListingFather>
  implements ListingFatherService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("shopShopName", "si.`shop_name`");
      put("regionName", "sr.`name`");
      put("classifyName", "c.`name`");
      put("brandName", "b.`name`");
      put("principalName", "su.`name`");
      put("pairProductName", "p.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected ListingFatherService self;

  @Resource
  protected ListingSmallRankService listingSmallRankService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected SysRegionMapper sysRegionMapper;

  @Resource
  protected ClassifyMapper classifyMapper;

  @Resource
  protected BrandMapper brandMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected ListingFatherRelievePairAction listingFatherRelievePairAction;

  @Autowired(required = false)
  protected ListingFatherBatchRelievePairAction listingFatherBatchRelievePairAction;

  @Autowired(required = false)
  protected ListingFatherSyncAmazonListingAction listingFatherSyncAmazonListingAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected ListingFatherSyncProductAction listingFatherSyncProductAction;

  @Resource
  protected Validator validator;

  /**
   * 创建Listing
   * @param model Listing
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(ListingFatherVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ListingFather entity = new ListingFather();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getPairStatus() == null) {
      entity.setPairStatus("0");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("Listing保存失败");
  }

  /**
   * 更新所有子表
   * @param model Listing
   */
  protected void updateAllChilds(ListingFatherVo model) throws Exception {
    if (model.getSmallRank() != null) {
      listingSmallRankService.saveAllByListingId(
        model.getId(),
        model.getSmallRank()
      );
    }
  }

  /**
   * 更新Listing
   * @param model Listing
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(ListingFatherVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ListingFather entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("Listing不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "msku",
      "asin",
      "productName",
      "sku",
      "shop",
      "createTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新Listing（带空值）
   * @param model Listing
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(ListingFatherVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ListingFather entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("Listing不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(ListingFather::getLastUpdateTime, model.getLastUpdateTime())
      .set(ListingFather::getLastUpdateUser, model.getLastUpdateUser())
      .set(ListingFather::getTitle, model.getTitle())
      .set(ListingFather::getRegion, model.getRegion())
      .set(ListingFather::getFbaFee, model.getFbaFee())
      .set(ListingFather::getReferralFee, model.getReferralFee())
      .set(ListingFather::getRemark, model.getRemark())
      .set(ListingFather::getProductRemark, model.getProductRemark())
      .set(ListingFather::getProductDescription, model.getProductDescription())
      .set(ListingFather::getBulletPoint, model.getBulletPoint())
      .set(ListingFather::getSearchTerms, model.getSearchTerms())
      .set(ListingFather::getAmazonClassify, model.getAmazonClassify())
      .set(ListingFather::getProductType, model.getProductType())
      .set(ListingFather::getSalesType, model.getSalesType())
      .set(ListingFather::getGtin, model.getGtin())
      .set(ListingFather::getProductCode, model.getProductCode())
      .set(ListingFather::getManufacturer, model.getManufacturer())
      .eq(ListingFather::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(ListingFatherSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 小类排名信息(smallRank) 对应的对象
    ListingSmallRankSearchParamPo smallRankSearchParam =
      new ListingSmallRankSearchParamPo();
    smallRankSearchParam.setDisableDataPremissions(true);
    smallRankSearchParam.setListingIdInList(ids);
    ListingSmallRankMapper localListingSmallRankMapper = ContextHolder
      .getApplicationContext()
      .getBean(ListingSmallRankMapper.class);
    smallRankSearchParam.applySqlSegments();
    List<Long> smallRankIdList = localListingSmallRankMapper.searchIds(
      smallRankSearchParam
    );
    if (!smallRankIdList.isEmpty()) {
      ListingSmallRankService localListingSmallRankService = ContextHolder
        .getApplicationContext()
        .getBean(ListingSmallRankService.class);
      localListingSmallRankService.batchDelete(smallRankIdList);
    }
  }

  /**
   * 删除Listing
   * @param id Listing的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除Listing
   * @param ids Listing的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<ListingFatherImportPo> excelToImportRow(
    ListingFatherImportPo row,
    Integer rowNumber,
    ListingFatherVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<ListingFatherImportPo> ir =
      new ImportRow<ListingFatherImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<ListingFatherImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new ListingFatherVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, ListingFatherImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00049")
        );
      ListingFatherVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getDistributionType())) {
      List<SysDictAllItem> distributionTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "distributionType",
          n -> sysDictService.getDictItems("SCM00108")
        );
      ListingFatherVo finalVo = vo;
      distributionTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getDistributionType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setDistributionType(i.getItemValue()),
          () ->
            ir.addError(
              "distributionType",
              String.format(
                "必须为 %s 中之一",
                distributionTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setTotalPrice(SheetUtils.tryToDecimal(row.getTotalPrice()));
    vo.setLandedPrice(SheetUtils.tryToDecimal(row.getLandedPrice()));
    vo.setPrice(SheetUtils.tryToDecimal(row.getPrice()));
    vo.setDiscounts(SheetUtils.tryToDecimal(row.getDiscounts()));
    vo.setAfnFulfillableQuantity(
      SheetUtils.tryToInteger(row.getAfnFulfillableQuantity())
    );
    vo.setReservedFcTransfers(
      SheetUtils.tryToInteger(row.getReservedFcTransfers())
    );
    vo.setReservedFcProcessing(
      SheetUtils.tryToInteger(row.getReservedFcProcessing())
    );
    vo.setReservedCustomerorders(
      SheetUtils.tryToInteger(row.getReservedCustomerorders())
    );
    vo.setAfnInboundWorkingQuantity(
      SheetUtils.tryToInteger(row.getAfnInboundWorkingQuantity())
    );
    vo.setAfnInboundShippedQuantity(
      SheetUtils.tryToInteger(row.getAfnInboundShippedQuantity())
    );
    vo.setAfnInboundReceivingQuantity(
      SheetUtils.tryToInteger(row.getAfnInboundReceivingQuantity())
    );
    vo.setAfnUnsellableQuantity(
      SheetUtils.tryToInteger(row.getAfnUnsellableQuantity())
    );
    vo.setFbaFee(SheetUtils.tryToDecimal(row.getFbaFee()));
    vo.setReferralFee(SheetUtils.tryToDecimal(row.getReferralFee()));
    vo.setFbmInventory(SheetUtils.tryToInteger(row.getFbmInventory()));
    vo.setReviewNum(SheetUtils.tryToInteger(row.getReviewNum()));
    if (StringUtils.hasText(row.getPairType())) {
      List<SysDictAllItem> pairTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "pairType",
          n -> sysDictService.getDictItems("SCM00109")
        );
      ListingFatherVo finalVo = vo;
      pairTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPairType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPairType(i.getItemValue()),
          () ->
            ir.addError(
              "pairType",
              String.format(
                "必须为 %s 中之一",
                pairTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setSaleDate(SheetUtils.tryToDate(row.getSaleDate()));
    SheetUtils.datePreviewFormat(row.getSaleDate(), row::setSaleDate);
    vo.setFirstOrderDate(SheetUtils.tryToDate(row.getFirstOrderDate()));
    SheetUtils.datePreviewFormat(
      row.getFirstOrderDate(),
      row::setFirstOrderDate
    );
    if (StringUtils.hasText(row.getPairStatus())) {
      List<SysDictAllItem> pairStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "pairStatus",
          n -> sysDictService.getDictItems("SCM00111")
        );
      ListingFatherVo finalVo = vo;
      pairStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPairStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPairStatus(i.getItemValue()),
          () ->
            ir.addError(
              "pairStatus",
              String.format(
                "必须为 %s 中之一",
                pairStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCurrency())) {
      List<SysDictAllItem> currencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "currency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      ListingFatherVo finalVo = vo;
      currencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "currency",
              String.format(
                "必须为 %s 中之一",
                currencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setQuantity(SheetUtils.tryToInteger(row.getQuantity()));
    vo.setPairUpdateTime(SheetUtils.tryToDateTime(row.getPairUpdateTime()));
    vo.setDiscountsBegDate(SheetUtils.tryToDate(row.getDiscountsBegDate()));
    SheetUtils.datePreviewFormat(
      row.getDiscountsBegDate(),
      row::setDiscountsBegDate
    );
    vo.setDiscountsEndDate(SheetUtils.tryToDate(row.getDiscountsEndDate()));
    SheetUtils.datePreviewFormat(
      row.getDiscountsEndDate(),
      row::setDiscountsEndDate
    );
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopShopName()) &&
      SheetUtils.isBlank(row.getShop())
    ) {
      ShopInfoSearchParamPo shopSearchParam = new ShopInfoSearchParamPo();
      shopSearchParam.setLimit(2); // 最大只返回二行记录
      shopSearchParam.setShopNameEq(SheetUtils.trim(row.getShopShopName()));
      shopSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopMatches = shopInfoMapper.search(shopSearchParam);
      if (shopMatches.size() == 0) {
        ir.addError("shopShopName", "未能在店铺中找到匹配的数据");
      } else if (shopMatches.size() > 1) {
        ir.addError("shopShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShop(shopMatches.get(0).getId());
      }
    }
    // 处理关联字段“站点”
    if (
      !SheetUtils.isBlank(row.getRegionName()) &&
      SheetUtils.isBlank(row.getRegion())
    ) {
      SysRegionSearchParamPo regionSearchParam = new SysRegionSearchParamPo();
      regionSearchParam.setLimit(2); // 最大只返回二行记录
      regionSearchParam.setNameEq(SheetUtils.trim(row.getRegionName()));
      regionSearchParam.applySqlSegments();
      List<SysRegionItemVo> regionMatches = sysRegionMapper.search(
        regionSearchParam
      );
      if (regionMatches.size() == 0) {
        ir.addError("regionName", "未能在站点中找到匹配的数据");
      } else if (regionMatches.size() > 1) {
        ir.addError("regionName", "关联不唯一，在站点中找到多个匹配的数据");
      } else {
        vo.setRegion(regionMatches.get(0).getId());
      }
    }
    // 处理关联字段“分类”
    if (
      !SheetUtils.isBlank(row.getClassifyName()) &&
      SheetUtils.isBlank(row.getClassify())
    ) {
      ClassifySearchParamPo classifySearchParam = new ClassifySearchParamPo();
      classifySearchParam.setLimit(2); // 最大只返回二行记录
      classifySearchParam.setNameEq(SheetUtils.trim(row.getClassifyName()));
      classifySearchParam.applySqlSegments();
      List<ClassifyItemVo> classifyMatches = classifyMapper.search(
        classifySearchParam
      );
      if (classifyMatches.size() == 0) {
        ir.addError("classifyName", "未能在分类管理中找到匹配的数据");
      } else if (classifyMatches.size() > 1) {
        ir.addError(
          "classifyName",
          "关联不唯一，在分类管理中找到多个匹配的数据"
        );
      } else {
        vo.setClassify(classifyMatches.get(0).getId());
      }
    }
    // 处理关联字段“品牌”
    if (
      !SheetUtils.isBlank(row.getBrandName()) &&
      SheetUtils.isBlank(row.getBrand())
    ) {
      BrandSearchParamPo brandSearchParam = new BrandSearchParamPo();
      brandSearchParam.setLimit(2); // 最大只返回二行记录
      brandSearchParam.setNameEq(SheetUtils.trim(row.getBrandName()));
      brandSearchParam.applySqlSegments();
      List<BrandItemVo> brandMatches = brandMapper.search(brandSearchParam);
      if (brandMatches.size() == 0) {
        ir.addError("brandName", "未能在品牌管理中找到匹配的数据");
      } else if (brandMatches.size() > 1) {
        ir.addError("brandName", "关联不唯一，在品牌管理中找到多个匹配的数据");
      } else {
        vo.setBrand(brandMatches.get(0).getId());
      }
    }
    // 处理关联字段“负责人”
    if (
      !SheetUtils.isBlank(row.getPrincipalName()) &&
      SheetUtils.isBlank(row.getPrincipal())
    ) {
      SysUserSearch principalSearchParam = new SysUserSearch();
      principalSearchParam.setLimit(2); // 最大只返回二行记录
      principalSearchParam.setNameEq(SheetUtils.trim(row.getPrincipalName()));
      principalSearchParam.applySqlSegments();
      List<SysUserItemVo> principalMatches = sysUserMapper.search(
        principalSearchParam
      );
      if (principalMatches.size() == 0) {
        ir.addError("principalName", "未能在用户中找到匹配的数据");
      } else if (principalMatches.size() > 1) {
        ir.addError("principalName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setPrincipal(
          principalMatches
            .stream()
            .map(SysUserItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“配对产品”
    if (
      !SheetUtils.isBlank(row.getPairProductName()) &&
      SheetUtils.isBlank(row.getPairProduct())
    ) {
      ProductSearchParamPo pairProductSearchParam = new ProductSearchParamPo();
      pairProductSearchParam.setLimit(2); // 最大只返回二行记录
      pairProductSearchParam.setNameEq(
        SheetUtils.trim(row.getPairProductName())
      );
      pairProductSearchParam.applySqlSegments();
      List<ProductItemVo> pairProductMatches = productMapper.search(
        pairProductSearchParam
      );
      if (pairProductMatches.size() == 0) {
        ir.addError("pairProductName", "未能在产品管理中找到匹配的数据");
      } else if (pairProductMatches.size() > 1) {
        ir.addError(
          "pairProductName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setPairProduct(pairProductMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<ListingFatherImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<ListingFatherImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            ListingFatherImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              ListingFatherImportPo row,
              AnalysisContext cxt
            ) {
              ListingFatherVo vo = new ListingFatherVo();
              ImportRow<ListingFatherImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<ListingFatherImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<ListingFatherImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      ListingFatherVo vo = new ListingFatherVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    ListingFatherSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00049")
      );
      exportOptions.addFieldMappingOption(
        "shop",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ListingFatherItemVo) r).getShopShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "region",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ListingFatherItemVo) r).getRegionName())
          )
      );
      exportOptions.addFieldMappingOption(
        "classify",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ListingFatherItemVo) r).getClassifyName())
          )
      );
      exportOptions.addFieldMappingOption(
        "brand",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ListingFatherItemVo) r).getBrandName())
          )
      );
      exportOptions.addFieldMappingOption(
        "distributionType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00108")
      );
      exportOptions.addFieldMappingOption(
        "principal",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ListingFatherItemVo) r).getPrincipalName())
          )
      );
      exportOptions.addFieldMappingOption(
        "pairType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00109")
      );
      exportOptions.addFieldMappingOption(
        "saleDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "firstOrderDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "pairStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00111")
      );
      exportOptions.addStringFields(
        "msku",
        "fnsku",
        "status",
        "asin",
        "title",
        "parentAsin",
        "productName",
        "sku",
        "shopShopName",
        "regionName",
        "classifyName",
        "brandName",
        "distributionType",
        "ranking",
        "sellerCategory",
        "lastStar",
        "principalName",
        "pairType",
        "productRemark",
        "pairStatus"
      );

      String fileName = String.format(
        "Listing(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00049");
    List<SysDictAllItem> distributionTypeItems = sysDictService.getDictItems(
      "SCM00108"
    );
    List<SysDictAllItem> pairTypeItems = sysDictService.getDictItems(
      "SCM00109"
    );
    List<SysDictAllItem> pairStatusItems = sysDictService.getDictItems(
      "SCM00111"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<ListingFatherExcelPo> items = new ArrayList<ListingFatherExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<ListingFatherItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<ListingFatherItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (ListingFatherItemVo item : list) {
        ListingFatherExcelPo excel = new ListingFatherExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        if (item.getDistributionType() != null) {
          distributionTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getDistributionType()))
            .findFirst()
            .ifPresent(i -> excel.setDistributionType(i.getItemText()));
        }
        if (item.getPairType() != null) {
          pairTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPairType()))
            .findFirst()
            .ifPresent(i -> excel.setPairType(i.getItemText()));
        }
        if (item.getPairStatus() != null) {
          pairStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPairStatus()))
            .findFirst()
            .ifPresent(i -> excel.setPairStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "Listing(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(ListingFatherExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过FNSKU查询Listing主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByFnsku(String fnsku) {
    return this.baseMapper.getIdByFnsku(fnsku);
  }

  /**
   * 通过FNSKU查询Listing多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByFnsku(List<String> list) {
    return this.baseMapper.getIdsByFnsku(list);
  }

  /**
   * 通过Listing主键查询FNSKU
   */
  @Override
  public String getFnskuById(Long id) {
    return this.baseMapper.getFnskuById(id);
  }

  /**
   * 通过Listing主键查询FNSKU列表
   */
  @Override
  public List<String> getFnskuByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getFnskuByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("fnsku"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id Listing的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public ListingFatherVo getVoById(Long id) throws Exception {
    ListingFatherVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    ListingSmallRankSearchParamPo smallRankSearchParamPo =
      new ListingSmallRankSearchParamPo();
    smallRankSearchParamPo.setListingId(id);
    smallRankSearchParamPo.getExtendData().put("queryMode", "sub");
    smallRankSearchParamPo.getExtendData().put("queryParent", "ListingFather");
    smallRankSearchParamPo.applySqlSegments();
    vo.setSmallRank(listingSmallRankService.search(smallRankSearchParamPo));

    return vo;
  }

  /**
   * 分页查询Listing
   * @param search 查询条件
   * @return Listing分页查询结果
   */
  @Override
  public Page<ListingFatherItemVo> pageSearch(
    ListingFatherSearchParamPo search
  ) {
    Page<ListingFatherItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(ListingFatherItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * Listing快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'ListingFatherOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<ListingFatherItemVo>> searchOptions(
    ListingFatherSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询Listing
   * @param search 查询条件
   * @return Listing列表查询结果
   */
  @Override
  public List<ListingFatherItemVo> search(ListingFatherSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询Listing最后更新时间
   * @param search 查询条件
   * @return Listing最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(ListingFatherSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 解除配对
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了解除配对操作"
  )
  @Override
  public void relievePair(Long id) throws Exception {
    if (listingFatherRelievePairAction == null) {
      throw new Exception("此操作当前不可用");
    }
    listingFatherRelievePairAction.run(id);
  }

  /**
   * 批量解除配对
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量解除配对操作"
  )
  @Override
  public void batchRelievePair(List<Long> ids) throws Exception {
    if (listingFatherBatchRelievePairAction == null) {
      throw new Exception("此操作当前不可用");
    }
    listingFatherBatchRelievePairAction.run(ids);
  }

  /**
   * 同步商品
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步商品操作"
  )
  @Override
  public void syncAmazonListing() throws Exception {
    if (listingFatherSyncAmazonListingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    listingFatherSyncAmazonListingAction.run();
  }

  /**
   * 同步店铺商品
   */
  /**
   * 同步店铺商品表单确定操作
   */
  @Override
  public void syncListingByShopConfirm(JSONObject data) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/ListingFather_syncListingByShop_confirm.js",
      data,
      this
    );
  }

  /**
   * 同步产品
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步产品操作"
  )
  @Override
  public void syncProduct() throws Exception {
    if (listingFatherSyncProductAction == null) {
      throw new Exception("此操作当前不可用");
    }
    listingFatherSyncProductAction.run();
  }
}
